//
//  MineViewController.m
//  TakeNotes
//
//  Created by 航汇聚 on 2019/5/17.
//  Copyright © 2019 BellaZhou. All rights reserved.
//
#import "MineViewController.h"
#import <IQKeyboardManager/IQKeyboardManager.h>
#import <SVProgressHUD/SVProgressHUD.h>
#import "UIViewController+Config.h"
#import "NSDate+Formatter.h"
#import "Money+CoreDataProperties.h"
#import "Account+CoreDataProperties.h"
#import "CoreDataStackManager.h"
#import "FetchRequestManager.h"
typedef NS_ENUM(NSInteger, FunctionCellType) {
    FunctionCellType_Aboutus = 0,
    FunctionCellType_Contactus,
    FunctionCellType_setting,
    FunctionCellType_colorStyle, //Dark or light
};
@interface MineViewController ()<UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UILabel *signDayNumberLabel;
@property (weak, nonatomic) IBOutlet UILabel *takeNotesTotalDayNumberLabel;
@property (weak, nonatomic) IBOutlet UILabel *takeNotesTotalNumberLabel;
@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UIImageView *userPortraitImgView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *buildVersionLabel;
@property (nonatomic, strong) Account *account;
@property (nonatomic, strong) NSArray *functionCellTypes;
@end
static NSString * const cellIdentifier = @"chartCell";
@implementation MineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configOriginalUI];
    [self loadCoreData];
    [kDefaultCenter addObserver:self selector:@selector(loadCoreData) name:notification_billHadUpdated object:nil];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleVersion"];
    self.buildVersionLabel.text = [NSString stringWithFormat:@"Copyright @ CQ%@",app_Version];
}
#pragma mark - gesture action
- (IBAction)tapPortraitImageGesture:(UITapGestureRecognizer *)sender {
    UIImagePickerController *pickerImageCon = [UIImagePickerController new];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImageCon.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    pickerImageCon.delegate = self;
    [self presentViewController:pickerImageCon animated:YES completion:nil];
}
#pragma mark - delgate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.functionCellTypes.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.textColor = [UIColor lightGrayColor];
    switch ([self.functionCellTypes[indexPath.row] integerValue]) {
        case FunctionCellType_Aboutus:
            cell.textLabel.text = @"关于我们";
            break;
        case FunctionCellType_Contactus:
            cell.textLabel.text = @"联系我们";
            break;
            default:
            break;
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch ([self.functionCellTypes[indexPath.row] integerValue]) {
        case FunctionCellType_Aboutus:
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://moyuzq.com"] options:@{} completionHandler:^(BOOL success) {
                
            }];
        }
            break;
        case FunctionCellType_Contactus:
        {
            //qqNumber就是你要打开的QQ号码， 也就是你的客服号码。
            NSString  *qqNumber=@"2101749880";
            NSURL *url;
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
                url= [NSURL URLWithString:[NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",qqNumber]];
            }else if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"tim://"]]) {
                url= [NSURL URLWithString:[NSString stringWithFormat:@"tim://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",qqNumber]];
            }else {
                url = [NSURL URLWithString:[NSString stringWithFormat:@"http://wpa.qq.com/msgrd?v=3&uin=%@&site=qq&menu=yes", qqNumber]];
            }
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                
            }];
        }
            break;
        case FunctionCellType_setting:
        {
            
        }
            break;
        case FunctionCellType_colorStyle:
        {
            NSLog(@"");
        }
            break;
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    NSLog(@"%@",textField.text);
    
    self.account.name = [UIDevice currentDevice].name;
    [[CoreDataStackManager shareInstance] save];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
    UIImage *originalImage = [info valueForKey:UIImagePickerControllerOriginalImage];
    [self.userPortraitImgView setImage:originalImage];
    NSLog(@"选择的信息：%@",info);
    self.account.portrait = UIImagePNGRepresentation(originalImage);
    [[CoreDataStackManager shareInstance] save];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - private
- (void)configOriginalUI {
    self.tableView.estimatedRowHeight = 44;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.estimatedSectionHeaderHeight = 0.01;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];
    
    [IQKeyboardManager sharedManager].enable = YES;
    self.userNameTextField.text = [UIDevice currentDevice].name;
    self.account.userID = 1;
    [[CoreDataStackManager shareInstance] save];
    if (self.account.portrait) {
        [self.userPortraitImgView setImage:[UIImage imageWithData:self.account.portrait]];
    }
}
- (void)loadCoreData {
    NSArray *allData = [self allMoneyData];
    self.takeNotesTotalNumberLabel.text =  [NSString stringWithFormat:@"%lu",(unsigned long)allData.count];
    
    int totalDayNumber = 0;
    NSString *tempLastDayStr = @"";
    for (Money *instance in allData) {
        NSString *currentDayStr = [instance.time dateToStringByFormatterString:@"yyyy-MM-dd"];
        if (![tempLastDayStr isEqualToString:currentDayStr]) {
            totalDayNumber++;
            tempLastDayStr = currentDayStr;
        }
    }
    self.takeNotesTotalDayNumberLabel.text =  [NSString stringWithFormat:@"%d",totalDayNumber];
}
#pragma mark - getter
- (Account *)account {
    _account = (Account *)[[FetchRequestManager fetchByEntityName:NSStringFromClass([Account class]) predicateDesc:[NSString stringWithFormat:@"userID == 1"] sortDescriptors:@[] isPredicate:YES] firstObject];
    if (!_account) {
        NSEntityDescription *entityDescription = [NSEntityDescription entityForName:NSStringFromClass([Account class]) inManagedObjectContext:CoreDataStackManager.shareInstance.managerContenxt];
        //加入到被管理对象上下文中。
        _account = [[Account alloc]initWithEntity:entityDescription insertIntoManagedObjectContext:CoreDataStackManager.shareInstance.managerContenxt];
    }
    return _account;
}
- (NSArray *)functionCellTypes {
    if (!_functionCellTypes) {
        _functionCellTypes = @[@(FunctionCellType_Aboutus), @(FunctionCellType_Contactus)];
    }
    return _functionCellTypes;
}
@end
